package com.dkd.sbtz.domain.ordervo.exportsheet;

// src/main/java/com/dkd/sbtz/service/export/ExcelSheets.java

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import java.util.List;
import java.util.function.BiConsumer;

public class ExcelSheets {

    /** 写一个 Sheet：headers + data(按 rowFiller 写每行) */
    public static <T> void writeSheet(SXSSFWorkbook wb, String sheetName,
                                      String[] headers, List<T> data,
                                      BiConsumer<Row, T> rowFiller) {
        Sheet sheet = wb.createSheet(sheetName);

        // header style
        CellStyle head = wb.createCellStyle();
        Font bold = wb.createFont();
        bold.setBold(true);
        head.setFont(bold);
        head.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        head.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        head.setBorderBottom(BorderStyle.THIN);
        head.setBorderTop(BorderStyle.THIN);
        head.setBorderLeft(BorderStyle.THIN);
        head.setBorderRight(BorderStyle.THIN);

        // body style（可按需扩展）
        CellStyle body = wb.createCellStyle();
        body.setBorderBottom(BorderStyle.THIN);
        body.setBorderTop(BorderStyle.THIN);
        body.setBorderLeft(BorderStyle.THIN);
        body.setBorderRight(BorderStyle.THIN);
        body.setWrapText(true);

        // header
        Row h = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            Cell c = h.createCell(i);
            c.setCellValue(headers[i]);
            c.setCellStyle(head);
            // 适当列宽（避免 autosize 带来的全表扫描）
            sheet.setColumnWidth(i, Math.min(10000, headers[i].length() * 1000 + 2000));
        }

        // body
        int r = 1;
        for (T d : data) {
            Row row = sheet.createRow(r++);
            rowFiller.accept(row, d);
            for (int i = 0; i < headers.length; i++) {
                Cell c = row.getCell(i);
                if (c == null) c = row.createCell(i);
                c.setCellStyle(body);
            }
        }
    }
}

